package com.sxj.PDMS.controller.student;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.model.dto.admin.MessageSelectRequest;
import com.sxj.PDMS.model.entity.Message;
import com.sxj.PDMS.model.entity.Student;
import com.sxj.PDMS.model.vo.MessageVO;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.MessageService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/student")
@Slf4j
public class StudentMessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/selectAll_message")
    public BaseResponse<PagingQueryResponse<Message>> selectMessage(@RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<Message> pagingQueryResponse = messageService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/select_message")
    public BaseResponse<PagingQueryResponse<MessageVO>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                                                            MessageSelectRequest messageSelectRequest) {

        PagingQueryResponse<MessageVO> pagingQueryResponse = messageService.messageSelect(page, pageSize, messageSelectRequest);

        return Result.success(pagingQueryResponse);
    }

    // todo 资料文件下载
    @ApiOperation(value = "downloadMessage", produces = "application/octet-stream")
    @GetMapping("/download_message")
    public void downloadMessage(HttpServletResponse response,
                                String downloadFile) throws Exception {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file", downloadFile);
        Message message = messageService.getOne(queryWrapper);
        if (message == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "库中没有该文件");
        }
        log.info("下载文件：{}", downloadFile);
        //todo://message存放位置
        String path = "D:\\user\\Desktop\\store\\message\\";
        OutputStream outPutStream;
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(downloadFile)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(path + "\\" + avatar);
                outPutStream = response.getOutputStream();
                outPutStream.write(bytes);
                outPutStream.flush();
                outPutStream.close();
            }
        } catch (Exception e) {
            System.out.println(avatar + "下载失败");
        }
    }

    @GetMapping("/message_detail/{id}")
    public BaseResponse<Message> messageDetail(@PathVariable String id) {

        return Result.success(messageService.getById(id));
    }
}
